String without aaa or bbb¶
Time: O(A+B); Space: O(1); easy
Given two integers A and B, return any string S such that: * S has length A + B and contains exactly A ‘a’ letters, and exactly B ‘b’ letters; * The substring ‘aaa’ does not occur in S; * The substring ‘bbb’ does not occur in S.
Example 1:
Input: A = 1, B = 2
Output: “abb”
Explanation:
“abb”, “bab” and “bba” are all correct answers.
Example 2:
Input: A = 4, B = 1
Output: “aabaa”
Notes:
0 <= A <= 100
0 <= B <= 100
It is guaranteed such an S exists for the given A and B.
[1]:
class Solution1(object):
"""
Time: O(A+B)
Space: O(1)
"""
def strWithout3a3b(self, A, B):
"""
:type A: int
:type B: int
:rtype: str
"""
result = []
put_A = None
while A or B:
if len(result) >= 2 and result[-1] == result[-2]:
put_A = result[-1] == 'b'
else:
put_A = A >= B
if put_A:
A -= 1
result.append('a')
else:
B -= 1
result.append('b')
return ''.join(result)
[4]:
s = Solution1()
A = 1
B = 2
assert s.strWithout3a3b(A, B) == "abb" or "abb" or "bab" or "bba"
A = 4
B = 1
assert s.strWithout3a3b(A, B) == "aabaa"